<template>
   <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon='Plus' @click="showTrademarkDialog">添加</el-button>
      </div>
    </template>

    <el-table :data="trademarkList" border style="width: 100%" v-loading='loading'>
        <el-table-column prop="date" align='center' type="index" label="序号" width="180" />
        <el-table-column prop="tmName" align='center' label="品牌" width="180" />
        <el-table-column prop="address" align='center' label="品牌LOGO" >
            <template v-slot="{row}">
                <img :src="row.logoUrl" alt="" style="width:100px;height:100px">
            </template>
        </el-table-column>
        <el-table-column prop="address" align='center' label="操作" >
            <template v-slot="{row,$index}">
            <el-button title="编辑" type="warning" size="small" :icon="Edit" @click="editTrademark(row)"/>
            <el-button title="删除" type="danger" size="small" :icon="Delete" @click="removeTrademark(row)" />
            </template>
        </el-table-column>
    </el-table>

    <!-- 添加或修改品牌之对话框 -->
    <!-- 第一次添加图片是没有id的 上传成功后服务器会自动给一个id 此时才有id 所以可通过有无id判断添加合适修改 -->
    <el-dialog v-model="dialogFormVisible" :title="`${TrademarkInfo.id?'修改':'添加'}品牌`">
    <el-form :rules="rules" :model="TrademarkInfo" ref="ruleFormRef">
      <el-form-item label="品牌名称" label-width="90px" prop="tmName">
        <el-input style="width: 80%;" autocomplete="off" v-model='TrademarkInfo.tmName'/>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="90px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="`${BASE_URL}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="TrademarkInfo.logoUrl" :src="TrademarkInfo.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png 文件，且不超过2M大小
             </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)" 
          >确 定</el-button>
      </span>
    </template>
  </el-dialog>

     <!-- 分页器 -->
  <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 12]" :small="small"
        :disabled="disabled" :background="background"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
  </el-card>
</template>

<script lang='ts'>
export default {
    name:'Trademark'
}
</script>

<script lang='ts' setup>
import {reqGetAllTrademarkListData,reqSaveTrademarkInfo,reqDeleteTrademarkInfo,reqUpdateTrademarkInfo} from '@/api/product/trademark'
import { Plus , Edit , Delete} from '@element-plus/icons-vue'
import type {TrademarkListModel,TrademarkModel} from '@/api/product/model/trademark';
import {onMounted, ref , reactive} from 'vue'
import { ElMessage, type UploadProps ,ElMessageBox} from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'


// 1.定义数据
let currentPage = ref(1)
let pageSize = ref(3)
// 在这里 数组仍用ref创建而非reactive创建，是因为reactive无法观测到数组地址的变化，
//     赋值后数据就不是响应式了
let trademarkList = ref<TrademarkListModel>([])
let total = ref(0) //品牌数量

const small = ref(false)
const disabled = ref(false)
const background = ref(false)
const loading = ref(true);

// 弹出对话框及上传图片时的变量值
const dialogFormVisible = ref(false)
const BASE_URL = import.meta.env.VITE_API_URL

const ruleFormRef = ref<FormInstance>() // 定义一个ref值 和el-form绑定

// 书写校验规则 
const rules = reactive<FormRules>({
  tmName:[
    { required: true, message: '请添加品牌名称', trigger: 'blur'},
    { min: 1, max: 15, message: '长度在1到15之间', trigger: 'blur'}
  ],
  logoUrl:[{required: true, message: '请选择要上传的图片', trigger: 'change'}]
})

// 定义一下要发给服务器的品牌数据
const initTrademark = ()=>({tmName:'',logoUrl:''})
const TrademarkInfo = reactive<TrademarkModel>(initTrademark())


// 2.定义一个获取分页数据的功能方法
const getTrademarkListData = async ()=>{
    const res = await reqGetAllTrademarkListData(currentPage.value,pageSize.value)
    console.log(res);
    
    trademarkList.value = res.records;

    total.value = res.total

    // 隐藏loading效果
    loading.value = false
}
onMounted(()=>{
    getTrademarkListData()
})

// 3.单击当前页码实现分页
const handleCurrentChange = (val:number)=>{
    currentPage.value = val
    getTrademarkListData()
}

// 4.修改每页显示的条数
const handleSizeChange = (val:number)=>{
    pageSize.value = val
    // 重新设置后 跳转到第一页
    currentPage.value = 1
    getTrademarkListData()
}

// 5.弹出品牌对话框 清空原值
function showTrademarkDialog(){
  // trademarkInfo.tmName = ''
  // trademarkInfo.logoUrl = ''
  // imageUrl.value = ''
  Object.assign(TrademarkInfo,initTrademark())
  delete TrademarkInfo.id // 清除id 要不然第一次上传后 此后不管是修改还是添加 标题都是修改
  dialogFormVisible.value = true

  // 清除上一次添加又取消留下的校验规则
  ruleFormRef.value?.clearValidate()
}

// 6.弹出框的确定按钮 上传品牌或修改品牌
const submitForm = async (formEl:FormInstance | undefined)=>{
  if(!formEl) return
  await formEl.validate(async(valid,fields)=>{
    if(valid){
      if (TrademarkInfo.id) {
        // 更新操作
        await reqUpdateTrademarkInfo(TrademarkInfo)
        ElMessage.success('品牌更新成功')
      }else{
        // 添加操作
        await reqSaveTrademarkInfo(TrademarkInfo)
        // 添加成功
        ElMessage({
          type:'success',
          message:'操作成功'
        });
        currentPage.value = 1
      } 
        // 关闭对话框
        dialogFormVisible.value = false
        getTrademarkListData()
    }else{
      console.log('error',fields);
    }
  })
}

// 7.图片上传成功
const handleAvatarSuccess:UploadProps['onSuccess'] = (response,uploadFile)=>{
  // 生成图片链接
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  TrademarkInfo.logoUrl = response.data

  // 清除表单验证
  ruleFormRef.value?.clearValidate(['logoUrl'])
}

// 8.图片上传前的校验
const beforeAvatarUpload:UploadProps['beforeUpload'] = rawFile => {
  const imgArr = ['image/jpeg','image/png','image/jpg']
  if(!imgArr.includes(rawFile.type)){
    ElMessage.error('图片格式不正确，应为.jpg/.png/.jpeg等');
    return false;
  }else if(rawFile.size / 1024 / 1024 > 2){
    ElMessage.error('图片大小不能超过2M，请重新上传');
    return false;
  }
  return true
}

// 9. 删除图片
const removeTrademark = (row:TrademarkModel) => {
  ElMessageBox.confirm(
    '你确认删除该图片吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(async () => {
      // debugger
      await reqDeleteTrademarkInfo(row.id as number);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 发送请求更新页面
      getTrademarkListData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 10.修改图片数据
const editTrademark = (row:TrademarkModel)=>{
  // 将需要显示出来的品牌数据给trademark进行赋值，因为数据是响应式的，页面会渲染出来
  Object.assign(TrademarkInfo,row) // 此时的row有id，因为当我们第一次上传图片数据时，服务器给了一个默认id
  dialogFormVisible.value = true

  // 清除上一次更新又取消的校验规则
  ruleFormRef.value?.clearValidate()
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>